<template>
  <div id="app">
    <button @click="add">添加</button>
    <table border="1">
      <thead>
        <tr>
          <th colspan="5">购物车</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>
            <input
              type="checkbox"
              v-model="checkAll"
              @change="checkedAll"
            />全选
          </td>
          <td>商品名称</td>
          <td>商品数量</td>
          <td>商品单价</td>
          <td>操作</td>
        </tr>
        <tr v-for="(phone, index) in list" :key="index">
          <td>
            <input
              type="checkbox"
              v-model="phone.isChecked"
              @change="checkedItem"
            />
          </td>
          <td>{{ phone.name }}</td>
          <td>
            <input type="text" v-model.number="phone.num" />
          </td>
          <td>{{ phone.price }}</td>
          <td>
            <button @click="del(index)">删除</button>
          </td>
        </tr>
        <tr>
          <td></td>
          <td>总计</td>
          <td>{{ totalNum }}件</td>
          <td>{{ totalPrice }}元</td>
          <td></td>
        </tr>
      </tbody>
    </table>
    <modal v-if="isShow" @suerAdd="getData"></modal>
  </div>
</template>

<script>
import modal from './modal'
export default {
  data() {
    return {
      // 弹窗是否显示
      isShow: false,
      list: [
        {
          name: "iphone 12",
          price: 6000,
          num: 2,
          isChecked: false,
        },
        {
          name: "huawei P40 pro",
          price: 5000,
          num: 5,
          isChecked: false,
        },
        {
          name: "mi 11",
          price: 4000,
          num: 8,
          isChecked: false,
        },
      ],
      // 是否全选
      checkAll: false,
    };
  },
  components: {
    modal
  },
  computed: {
    // 计算总数量
    totalNum() {
      let num = 0;
      this.list.forEach((item) => {
        num += item.num;
      });
      return num;
    },
    // 计算总金额
    totalPrice() {
      let num = 0;
      this.list.forEach((item) => {
        num += item.num * item.price;
      });
      return num.toFixed(2);
    },
  },
  methods: {
    // 点击添加按钮，显示弹窗
    add() {
      this.isShow = true;
    },
    // 弹窗组件传过来的值
    getData(info) {
      // console.log(info);
      this.list.push(info);
      this.isShow = false;
    },
    del(index) {
      // 删除购物车中的某一项
      this.list.splice(index, 1);
    },
    // 全选按钮
    checkedAll() {
      this.list.forEach((item) => {
        item.isChecked = this.checkAll;
      });
    },
    // 每件商品的选择
    checkedItem() {
      this.checkAll = this.list.every((item) => {
        return item.isChecked;
      });
    },
  },
};
</script>

<style>
 
</style>